package com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import com.romotc.json.tools.Jackson;
import com.romotc.qqrobot.bean.QQLogedin;
import com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor.DateProcessor;
import com.romotc.scache.RequestSpy;
/**
 * 专门转换json字符串为java bean的公共处理类
 * @author romotc
 * @param <T>
 *
 */
public class JsonDataProcessor<T> implements DateProcessor {

	/**
	 * 获取process对象 以后可以加上对象的缓存机制
	 * @param valueType 要转换的json javaben类型
	 * @param reqDataObjKey 放置到reqDataObj中的key值
	 * @return
	 */
	public static <T> JsonDataProcessor getInstance(Class<T> valueType, String reqDataObjKey) {
		return new JsonDataProcessor(valueType, reqDataObjKey);
	}
	
	private Class<T> valueType;
	private String reqDataObjKey;
	public JsonDataProcessor(Class<T> valueType, String reqDataObjKey) {
		this.valueType = valueType;
		this.reqDataObjKey = reqDataObjKey;
	}
	
	
	@Override
	public JSONObject processResponse(QQLogedin loginQQ, RequestSpy rqSpy,
			JSONObject reqDataObj) throws Exception {
		
		String resBody = rqSpy.getResBody();
		
		//去除特殊符号
		if(StringUtils.isBlank(resBody)) { 
			return reqDataObj;
		}	
		
		resBody = resBody.replace("\\x20", "").replace("\\x7E", "");
		resBody = resBody.replace("\\x", "");
		T data = Jackson.getObjectMaper().readValue(resBody, valueType);

		reqDataObj.put(reqDataObjKey, data);
		return reqDataObj;
	}

}
